package com.littlec.sdk.business;

import java.io.File;
import java.io.IOException;
import java.util.Collection;

import org.apache.harmony.javax.security.sasl.SaslException;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Presence;

import android.text.TextUtils;

import com.littlec.sdk.CMChatConfig;
import com.littlec.sdk.XMPPConnectionManager;
import com.littlec.sdk.entity.EnumLoginStatus;
import com.littlec.sdk.manager.CMIMHelper;
import com.littlec.sdk.utils.CMChatGlobalStorage;
import com.littlec.sdk.utils.CMChatListener;
import com.littlec.sdk.utils.MyLogger;
import com.littlec.sdk.utils.NetworkUtil;

public class Login {
	public static final MyLogger sLogger = MyLogger.getLogger("Login");
	private static Login mLogin = null;

	private void handleActionCode(int code,
			CMChatListener.OnCMListener mListener) {
		try {
			switch (code) {
			case 1:
				if (NetworkUtil.isNetworkConnected(CMIMHelper
						.getCmAccountManager().getApplicationContext()))
					loginFailed("用户名或密码错误，请重新填写", mListener);
				else
					loginFailed("用户名或密码错误，请重新填写", mListener);
				break;
			case 2:
				loginFailed("登录超时", mListener);
				break;
			case 3:
				loginFailed("无法连接到服务器，请检查你的网络或稍后重试", mListener);
				break;
			case 4:
				sLogger.d("#######loginSuccess####");
				CMChatGlobalStorage.getInstance().setLoginStatus(
						EnumLoginStatus.STATE_LOGINED);
				configurePath();
				CMIMHelper.getCmAccountManager().getCurrentAccount();
				if (mListener != null) {
					mListener.onSuccess();
				}
				break;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static Login getInstance() {
		synchronized (Login.class) {
			if (mLogin == null) {
				mLogin = new Login();
			}
		}
		return mLogin;
	}

	public void doLogin(String userName, String passWord,
			final CMChatListener.OnCMListener mListener) {
//		com.im.XmppConnectionManager.getInstance().init();
//	    new Thread(){  
//	        @Override  
//	        public void run()  
//	        {  
//	        	XMPPConnection connection1 = com.im.XmppConnectionManager.getInstance()
//	    				.getConnection();
//	    		try {
//	    			connection1.connect();
//	    			connection1.login("15025443417", "123456");
//	    			connection1.sendPacket(new Presence(Presence.Type.available));
//	    		} catch (XMPPException e) {
//	    			e.printStackTrace();
//	    		}
//	       }  
//	     }.start();  
		
		StringBuffer errorDesc = new StringBuffer("");
		if (!checkLoginDataValidation(userName, passWord, errorDesc)) {
			loginFailed(errorDesc.toString(), mListener);
			return;
		}
		if (!NetworkUtil.isNetworkConnected(CMIMHelper.getCmAccountManager()
				.getApplicationContext())) {
			loginFailed("连接服务器失败，请检查你的网络或稍后重试", mListener);
			return;
		}
		userName = userName.toLowerCase();
		CMChatGlobalStorage.getInstance().setLoginUserName(userName);
		CMChatGlobalStorage.getInstance().setLoginPassWord(passWord);
		if (CMChatGlobalStorage.getInstance().getLoginStatus() == EnumLoginStatus.STATE_LOGINING) {
			return;
		}
		Login.this.doXMPPLogin(mListener);
	}

	private boolean checkLoginDataValidation(String userName, String passWord,
			StringBuffer errorDesc) {
		if (TextUtils.isEmpty(userName)) {
			errorDesc = errorDesc.append("用户名不能为空！");
			return false;
		}

		if (TextUtils.isEmpty(passWord)) {
			errorDesc = errorDesc.append("密码不能为空！");
			return false;
		}

		// if (!SdkUtils.checkUserName(userName)) {
		// errorDesc = errorDesc.append(userName + "," + "�û���Ϸ�������������");
		// return false;
		// }
		// if (!SdkUtils.checkPassWord(passWord, false)) {
		// errorDesc = errorDesc.append("���벻�Ϸ�������������");
		// return false;
		// }

		return true;
	}

	private void loginFailed(String errorMsg,
			CMChatListener.OnCMListener mListener) {
		CMChatGlobalStorage.getInstance().setLoginStatus(
				EnumLoginStatus.STATE_NONE);
		if (mListener != null)
			mListener.onFailed(errorMsg);
	}

	private synchronized void doXMPPLogin(
			final CMChatListener.OnCMListener mListener) {
		sLogger.d("doXMPPLogin");
		new Thread() {
			public void run() {
				Login.this.doXMPPLoginServer(mListener);
			}
		}.start();
	}

	private synchronized void doXMPPLoginServer(
			CMChatListener.OnCMListener mListener) {
		try {
			sLogger.d("xmpp begin to connect, waiting 3min later will timeout");
			CMChatGlobalStorage.getInstance().setLoginStatus(
					EnumLoginStatus.STATE_LOGINING);
			connectXMPPServer();
			
			XMPPConnection connection = XMPPConnectionManager.getInstance()
					.getConnection();
			if (CMChatGlobalStorage.getInstance().getLoginStatus() == EnumLoginStatus.STATE_NONE) {
				if (connection.isConnected()) {
					XMPPConnectionManager.getInstance().disconnect();
				}
				return;
			}
			if (connection == null) {
				sLogger.e("xmpp connect failue ��connection == null");
				handleActionCode(2, mListener);

				return;
			}

			if (!connection.isAuthenticated()) {
				connection.login(CMChatGlobalStorage.getInstance().getmLoginUserName(), CMChatGlobalStorage.getInstance().getmLoginPassWord());
//				connection.sendPacket(new Presence(Presence.Type.available));
			}
				
			handleActionCode(4, mListener);
//			Presence presence1 = new Presence(Presence.Type.unavailable);  
//            connection.sendPacket(presence1); 
//			connection.connect();
		} catch (SaslException e) {
			sLogger.e("xmpp connect failue ��SaslException, wrong username or password");
			dealException(e, 1, mListener);
		} catch (IOException e) {
			sLogger.e("xmpp connect failue ��IOException");
			dealException(e, 3, mListener);
		} catch (XMPPException e) {
			sLogger.e("xmpp connect failue ��XMPPException,saslError not authorized");
			dealException(e, 1, mListener);
		} catch (Exception e) {
			sLogger.e("xmpp connect failue ��ConnectionException");
			dealException(e, 3, mListener);
		}
	}

	private synchronized boolean connectXMPPServer() throws IOException,
			XMPPException {
		XMPPConnection connection = XMPPConnectionManager.getInstance()
				.getConnection();
		if (connection == null) {
			XMPPConnectionManager.getInstance().init(
					CMChatConfig.ServerConfig.getIM_HOST(),
					CMChatConfig.ServerConfig.getImPort());
			connection = XMPPConnectionManager.getInstance().getConnection();
		}
		if (connection.isConnected()) {
			return true;
		}
		connection.connect();
		CMChatConfig.ServerConfig.xmppServiceName = connection.getServiceName();
		CMChatConfig.ServerConfig.xmppConferenceServiceName = "conference."
				+ CMChatConfig.ServerConfig.xmppServiceName;
		return true;
	}

	private void configurePath() {
		CMChatGlobalStorage.MTC_DOWNLOAD_PATH = CMChatGlobalStorage.MTC_DATA_PATH
				+ "/download/" + "personal";
		CMChatGlobalStorage.MTC_DOWNLOAD_THUMBNAIL_SMALL_PATH = CMChatGlobalStorage.MTC_DOWNLOAD_PATH
				+ "/Thumbnail_Small";
		CMChatGlobalStorage.MTC_DOWNLOAD_THUMBNAIL_MIDDLE_PATH = CMChatGlobalStorage.MTC_DOWNLOAD_PATH
				+ "/Thumbnail_Middle";
		File thumbnailFile = new File(
				CMChatGlobalStorage.MTC_DOWNLOAD_THUMBNAIL_SMALL_PATH);
		if (!thumbnailFile.exists()) {
			thumbnailFile.mkdirs();
		}
		thumbnailFile = new File(
				CMChatGlobalStorage.MTC_DOWNLOAD_THUMBNAIL_MIDDLE_PATH);
		if (!thumbnailFile.exists())
			thumbnailFile.mkdirs();
	}

	private void dealException(Exception e, int code,
			CMChatListener.OnCMListener mListener) {
		if (e != null) {
			e.printStackTrace();
		}
		XMPPConnectionManager.getInstance().disconnect();

		handleActionCode(code, mListener);
	}

	public void destory() {
		mLogin = null;
	}
}
